package com.github.server.core;

import com.github.livebase.util.base.ByteArray;
import com.github.livebase.util.base.ObjectsUtil;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import fi.iki.elonen.NanoHTTPD;

/**
 * @ClassName HttpResponse
 * @description:
 * @author: biao532
 * @create: 2024-01-31 22:49
 * @Version 1.0
 **/
public class HttpResponse extends NanoHTTPD.Response implements com.github.server.interfaces.HttpResponse {
    private ByteArray array;
    public HttpResponse() {
        super(Status.OK, null, ObjectsUtil.Empty.INPUTSTREAM, 0);
    }
    public HttpResponse(IStatus status, String mimeType, InputStream data, long totalBytes) {
        super(status, mimeType, data, totalBytes);
    }
    @Override
    public void setCode(int code) {
        super.setStatus(Status.lookup(code));
    }

    @Override
    public void write(byte[] bs, int offset, int len) throws IOException {
        if (array == null) {
            array = new ByteArray(512);
        }
        array.append(bs, offset, len);
    }

    @Override
    public OutputStream getOutputStream() throws IOException {
        if (array == null) {
            array = new ByteArray();
        }
        return new OutputStream() {
            @Override
            public void write(byte[] b, int off, int len) throws IOException {
                array.append(b, off, len);
            }

            @Override
            public void write(int b) throws IOException {
                array.append((byte) b);
            }
        };
    }

    @Override
    protected void send(OutputStream outputStream) {
        if (array != null) {
            super.addHeader("content-length", String.valueOf(array.length()));
            super.setData(array.toInputStream());
        }
        super.send(outputStream);
    }
}
